package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
@Service
@Slf4j
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    @Override
    public ResponseResult login(AdUser adUser) {
        if(adUser==null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断用户密码和账户是否同时输入
        if(StringUtils.isBlank(adUser.getName()) || StringUtils.isBlank(adUser.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "用户名或密码不能为空");
        }
        //根据用户名查询用户并判断是否存在
        AdUser user = this.getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, adUser.getName()));
        if(user==null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户名不对");
        }
        //4.对比密码，如果对比成功，则生成token响应数据
        String loginPassword = adUser.getPassword();
        String dbpsd = user.getPassword();
        Boolean flag = BCrypt.checkpw(loginPassword,dbpsd);
        if (flag){
            //使用用户的id生成令牌
            String token = AppJwtUtil.getToken(user.getId().longValue());
            //封装响应的数据给前端
            Map map = new HashMap<>();
            map.put("token",token);
            user.setPassword("");
            map.put("user",user);
            return  ResponseResult.okResult(map);

        }else {
            //5.如果对比失败，响应密码错误
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }


    }
}
